package org.wtframework.platform.server.service;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.openredhead.springx.core.server.dao.support.IPageDao;
import org.openredhead.springx.core.server.model.IUser;
import org.openredhead.springx.core.server.service.Securitys;
import org.openredhead.springx.core.web.mvc.ajaxrpc.BasicAjaxRpcRemoteService;
import org.openredhead.springx.core.web.mvc.annotation.AjaxRpcMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wtframework.platform.server.manager.impl.UserManager;
import org.wtframework.platform.server.model.impl.User;

@Service
public class UserService extends BasicAjaxRpcRemoteService {

	@Autowired
	private UserManager userManager;

	@AjaxRpcMethod
	public User editUser(User user) {

		System.out.println("Ajax Rpc 信息：设置User，id设置值为：" + user.getId());
		System.out.println("Ajax Rpc 信息：设置User，username设置值为：" + user.getUsername());
		System.out.println("Ajax Rpc 信息：设置User，establishDate设置值为：" + user.getEstablishDate());

		User buser = userManager.load(user.getId());
		buser.setNickname(user.getNickname());
		userManager.save(buser);

		return buser;

		// throw new RuntimeException("又cccdsfa");

		// Integer.parseInt("1233x");

	}

	@AjaxRpcMethod
	//@NoSecutity
	public User getUser(long userId) {

		return userManager.load(userId);

	}
	
	public IPageDao<User> getUserList(List<Long> idList){
		String hql = "from User where id in (:idList)";
		if(idList.size()==0){
			return null;
		}
		return userManager.findByQuery(hql, "idList", idList);
	}
	
	/**
	 * 
	 * <B>方法描述：</B>（查询所有的老师） <br/>
	 *
	 * <B>作者：	 </B> 郑勇涛 <br/>
	 * <B>创建日期：</B> 2014年11月17日 下午3:09:03 
	 * @param identity
	 * @return
	 */
	@AjaxRpcMethod
	public List<User> searAllteacher(Integer identity){
		String hql = "from User where identity_id=?";
		return userManager.findByQuery(hql, identity).getList();
		
	}
	
	@AjaxRpcMethod
	public Boolean checkPassword(String oldPassword){
		
		if(!Securitys.isAnonymousUser()){
			IUser user = Securitys.getAuthenticationUser().getUser();
			String dataPassword = user.getPassword();
			oldPassword = DigestUtils.md5Hex(oldPassword);
			if(oldPassword.equals(dataPassword)){
				return true;
			}
		}
		return false;
	}
	
	@AjaxRpcMethod
	public Boolean updatePassword(String oldPassword, String newPassword){
		
		try {
			if(checkPassword(oldPassword)){
				IUser loginuser = Securitys.getAuthenticationUser().getUser();
				newPassword = DigestUtils.md5Hex(newPassword);
				loginuser.setPassword(newPassword);
				Long userId = loginuser.getId();
				User user = userManager.load(userId);
				user.setPassword(newPassword);
				userManager.save(user);
			}
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
		
	}

}
